import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { SESSION_COOKIE_NAME, VIP_STATUS } from '@/lib/types/session';
import { SessionRepository } from '@/lib/database/repositories/session-repository';

// 获取VIP状态
export async function GET() {
  try {
    const cookieStore = await cookies();
    const sessionCookie = cookieStore.get(SESSION_COOKIE_NAME);
    
    if (!sessionCookie) {
      return NextResponse.json({ status: VIP_STATUS.NORMAL });
    }
    
    const session = await SessionRepository.getById(sessionCookie.value);
    
    if (!session || session.expiresAt < new Date()) {
      return NextResponse.json({ status: VIP_STATUS.NORMAL });
    }
    
    return NextResponse.json({ 
      status: session.isVip ? VIP_STATUS.VIP : VIP_STATUS.NORMAL 
    });
    
  } catch (error) {
    console.error('获取VIP状态失败:', error);
    return NextResponse.json(
      { error: '获取VIP状态失败' },
      { status: 500 }
    );
  }
}

// 设置VIP状态
export async function POST(request: NextRequest) {
  try {
    const { isVip } = await request.json();
    const cookieStore = await cookies();
    const sessionCookie = cookieStore.get(SESSION_COOKIE_NAME);
    
    if (!sessionCookie) {
      return NextResponse.json(
        { error: '未找到会话' },
        { status: 400 }
      );
    }
    
    const session = await SessionRepository.getById(sessionCookie.value);
    
    if (!session || session.expiresAt < new Date()) {
      return NextResponse.json(
        { error: '会话已过期' },
        { status: 400 }
      );
    }
    
    // 更新VIP状态
    await SessionRepository.setVipStatus(session.id, Boolean(isVip));
    
    return NextResponse.json({ 
      status: Boolean(isVip) ? VIP_STATUS.VIP : VIP_STATUS.NORMAL,
      success: true
    });
    
  } catch (error) {
    console.error('设置VIP状态失败:', error);
    return NextResponse.json(
      { error: '设置VIP状态失败' },
      { status: 500 }
    );
  }
} 